﻿namespace HostedServiceDemo;

public class HostedService1 : BackgroundService
{
    private readonly TestService testService;
    private readonly IServiceScope serviceScope;


    /// <summary>
    /// 方法1: 构造函数服务注入（只能注入单例服务）
    /// </summary>
    /// <param name="testService"></param>
    //public HostedService1(TestService testService)
    //{
    //    this.testService = testService;
    //}


    /// <summary>
    /// 方法2: 通过IServiceScopeFactory，创建服务
    /// </summary>
    /// <param name="serviceScopeFactory"></param>
    public HostedService1(IServiceScopeFactory serviceScopeFactory)
    {
        var serviceScope = serviceScopeFactory.CreateScope();
        testService = serviceScope.ServiceProvider.GetService<TestService>();       // 此处应该在具体的逻辑中创建
    }



    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Console.WriteLine("HostedService1 服务启动...");
        await Task.Delay(4000, stoppingToken);
        var content = await File.ReadAllTextAsync(Path.Combine( Environment.CurrentDirectory, "Resource", "01.json"), stoppingToken);
        Console.WriteLine(content);
        Console.WriteLine(testService.Add(1,2));
    }

}
